<?php


namespace app\admin\controller;

use app\admin\service\SettingService;
use app\BaseController;
use think\App;
use think\facade\View;
use think\response\Json;

class Setting extends BaseController
{
    protected $service;

    /**
     * Category constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->service = app()->make(SettingService::class);
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(): string
    {
        $list = $this->service->queryList();
        $data['list'] = $list;
        return View::fetch('index', $data);
    }

    public function add(): string
    {
        return View::fetch('add');
    }

    public function save(): Json
    {
        $post = $this->request->post();
        if (!empty($post['names'])) {
            foreach ($post['names'] as $key=>$name) {
                $data = array();
                $data['name'] = $name;
                $data['value'] = $post['values'][$key];
                $dbData = $this->service->queryByName($name);
                if (!empty($dbData)) {
                    $data['id'] = $dbData->toArray()['id'];
                }
                $this->service->save($data);
            }
        }
        return success(true);
    }

    public function delete(): Json
    {
        return success($this->service->delete(input("id")));
    }
}